package com.beone.admin.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.po.TableField;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.base.SuperController;
import com.base.common.RequestContextUtils;
import com.beone.WorkshopMysqlGenerator;
import com.beone.generator.FormField;
import com.beone.generator.FormInfo;
import com.beone.generator.WebAutoGenerator;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @title  基于Web页面代码生成器
 * @Author 覃球球
 * @Version 1.0 on 2018/11/1.
 * @Copyright 贝旺科技
 */
@Controller
@RequestMapping("/auto")
public class WebGeneratorController extends SuperController{

    @Value("${spring.profiles.active}")
    private String devMode;

    private WebAutoGenerator autoGenerator;

    private boolean isDevMode(){
        return "dev".equals(devMode);
    }

    /** 数据库表信息 */
    private List<FormInfo>  formList  = new ArrayList<FormInfo>();

    Map<String, Object> formMap = new HashMap<String, Object>();

    @PostConstruct
    public void init(){
        if(isDevMode()){
            autoGenerator = (WebAutoGenerator) WorkshopMysqlGenerator.initAutoGeneratorConfig();
            autoGenerator.initConfig();

            initFormFiled(autoGenerator.getAllTableInfoList()); //初始化表单项配置信息
        }
    }

    /**
     * 显示模块配置页
     * @param model
     * @return
     */
     @GetMapping("/config")
     public String showConfig(ModelMap model){
         if(!isDevMode()){
             return "forward:/error/404";
         }
         model.addAttribute("formList", formList);
         return "vm/config";
     }

    /**
     * 显示模块配置页
     * @param model
     * @return
     */
    @GetMapping("/next")
    public String next(ModelMap model){
        if(!isDevMode()){
            return "forward:/error/404";
        }

        model.addAttribute("formList", formList);
        return "vm/next";
    }


    /**
     * 生成代码文件
     * @return
     */
    @PostMapping(value = "/generator", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Object generatorCode(){
        if(!isDevMode()){
            return super.responseResult("fail","该操作只能为dev环境！");
        }

        autoGenerator.getConfig().getGlobalConfig().setOpen(false);

        // 代码生成器
        autoGenerator.setCfg(new InjectionConfig() { // 注入自定义配置，可以在 VM 中使用 cfg.abc 设置的值
                @Override
                public void initMap() {
                    this.setMap(formMap);
                }
            }.setFileOutConfigList(WorkshopMysqlGenerator.getFileOutCOnfig("web"))
        );
        autoGenerator.execute();
        return  super.responseResult("success","保存成功！");
    }

    /**
     * 保存配置
     * @param request
     * @return
     */
    @PostMapping(value = "/save", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Object saveconfig(HttpServletRequest request) throws Exception{
        if(!isDevMode()){
            return super.responseResult("fail","该操作只能为dev环境！");
        }

        String tableName = request.getParameter("tableName");
        String fields = request.getParameter("fields");


        List<FormField> formFields =  JSON.parseArray(fields, FormField.class);
        formFields = setFormField(tableName, formFields);
        formMap.put(tableName, formFields);
        return  super.responseResult("success","配置保存成功！");
    }


    /**
     * 初始化formFields
     * @return
     */
    private void initFormFiled(List<TableInfo> tableList) {
        for(int i = 0; i < tableList.size(); i++){
            TableInfo table = tableList.get(i);
            FormInfo formInfo = new FormInfo();
            formInfo.setComment(table.getComment());
            formInfo.setEntityName(table.getEntityName());
            formInfo.setTableName(table.getName());

            List formFields = (List) formMap.get(table.getName());
            if(formFields == null){ //根据表名 没有获取到保存的formField信息
                List<TableField> tableFields = table.getFields();
                formFields = new ArrayList();
                for(int j = 0; j < tableFields.size(); j++){
                    TableField field = tableFields.get(j);
                    FormField ff = new FormField();
                    ff.setLabelName(StringUtils.isNotEmpty(field.getComment()) ? field.getComment() : field.getPropertyName());
                    ff.setPrimaryKey(field.isKeyFlag());
                    ff.setFormFieldName(field.getPropertyName());

                    if("Date".equals(field.getPropertyType())){
                        ff.setFormType("date");
                    }
                    formFields.add(ff);
                }
            }
            formInfo.setFields(formFields);
            formList.add(formInfo);
        }
    }

    /**
     * 根据tableName 给表单属性赋值
     * @param tableName
     * @return
     */
    private List<FormField> setFormField(String tableName, List formFields) throws Exception{
        List<FormField> fields = null;
        if(formFields == null || formFields.size() == 0){
            return fields;
        }

        for(int i = 0; i < formList.size(); i++){
            FormInfo form = formList.get(i);
            if(form.getTableName().equals(tableName)){
                fields = form.getFields();
                for(int j = 0; j < fields.size(); j++){
                    FormField field = fields.get(j);
                    for(int k = 0; k < formFields.size(); k++){
                        FormField ff = (FormField) formFields.get(k);
                        if(field.getFormFieldName().equals(ff.getFormFieldName())){
                            boolean keyFlag = field.isPrimaryKey();
                            BeanUtils.copyProperties(field, ff);
                            field.setPrimaryKey(keyFlag);
                            break;
                        }
                    }
                }
                break;
            }
        }
        return fields;
    }
}